/**
 * Alibaba.com.cn Inc.
 * Copyright (c) 2004-2021 All Rights Reserved.
 */
package com.yongbao.common.interceptor;

import com.yongbao.common.Constants;
import com.yongbao.common.enums.TerminalEnum;
import com.yongbao.context.BaseSession;
import com.yongbao.context.SessionContext;
import com.yongbao.model.vo.AdminVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zhanghong
 * @version HeaderInterceptor.java, v 0.1 2023/6/22 21:48 下午 HeaderInterceptor Exp $$
 */
@Slf4j
public class HeaderInterceptor implements AsyncHandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String terminal = request.getHeader(Constants.TERMINAL);
        if (terminal == null) {
            return false;
        }
        TerminalEnum terminalEnum = TerminalEnum.getByName(terminal);
        if (terminalEnum == null) {
            return false;
        }

        if (terminalEnum == TerminalEnum.PC) {
            Object object = request.getSession().getAttribute(Constants.LOGIN_ADMIN);
            if (object instanceof AdminVO) {
                AdminVO adminVO = (AdminVO) object;
                SessionContext.context.set(BaseSession.builder().adminVO(adminVO).terminalEnum(terminalEnum).build());
            }
        } else if (terminalEnum == TerminalEnum.WECHAT) {
            String token = request.getHeader(Constants.TOKEN);
            if (StringUtils.isNotBlank(token)) {
                SessionContext.context.set(BaseSession.builder().token(token).terminalEnum(terminalEnum).build());
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        SessionContext.context.remove();
    }
}
